package org.lex.net.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.log4j.Logger;

/**
 * @author Liu Er Xiao
 * @version 1.0, 2009-2-22
 */
public class SendResult {
	private final HttpMethod method;
	private final int statusCode;
	private final InputStream inputStream;
	private final String senderCharset;

	private String response = null;
	private Logger log = Logger.getLogger(SendResult.class);

	public SendResult(HttpMethod method, String charset) throws IOException {
		this.method = method;
		this.statusCode = method.getStatusCode();
		this.inputStream = method.getResponseBodyAsStream();
		this.senderCharset = charset.trim();
	}

	public int getStatusCode() {
		return statusCode;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public Reader getReader() throws UnsupportedEncodingException {
		return new InputStreamReader(inputStream, getResponseCharset());
	}

	public String getCharset() {
		return senderCharset;
	}

	public String getResponse() throws IOException {
		if (null == response) {
			String charset = getResponseCharset();
			log.info("Response charset=" + charset);
			response = readStream(inputStream, charset);
		}
		return response;
	}

	public void releaseConnection() {
		try {
			method.releaseConnection();
		} catch (RuntimeException e) {
			log.error("Release connection failed", e);
		}
	}

	private String getResponseCharset() {
		Header[] headers = method.getResponseHeaders();
		if (null == headers) {
			return senderCharset;
		}
		for (Header h : headers) {
			String header = h.toExternalForm();
			int index = header.indexOf("charset=");
			if (-1 != index) {
				int end = header.indexOf(';', index);
				if (-1 == end) {
					end = header.length();
				}
				String cs = header.substring(index + "charset=".length(), end);
				log.debug("Found charset from response header: " + header);
				return cs.trim();
			}
		}
		log.warn("Charset not found in response message");
		return senderCharset;
	}

	static String readStream(InputStream in, String charset) throws IOException {
		StringBuilder buf = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in, charset));
		char[] charBuf = new char[128];
		while (true) {
			int len = reader.read(charBuf);
			if (-1 == len) {
				break;
			} else {
				buf.append(charBuf, 0, len);
			}
		}
		return buf.toString();
	}
}
